<template>
  <div class="home">
    <div class="news-detail">
      <!-- 面包屑导航 -->
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>{{ news.category }}</el-breadcrumb-item>
        <el-breadcrumb-item>{{ news?.title || "新闻详情" }}</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- 加载状态 -->
      <el-skeleton :loading="loading" animated :rows="10" v-if="loading">
        <template #template>
          <div style="padding: 20px">
            <el-skeleton-item variant="h1" style="width: 80%" />
            <div style="margin: 20px 0">
              <el-skeleton-item variant="text" style="margin-right: 16px" />
              <el-skeleton-item variant="text" style="width: 30%" />
            </div>
            <el-skeleton-item variant="p" style="width: 100%" />
            <el-skeleton-item variant="p" style="width: 100%" />
            <el-skeleton-item variant="p" style="width: 100%" />
          </div>
        </template>
      </el-skeleton>

      <!-- 错误状态 -->
      <template v-else-if="error">
        <div class="error-container">
          <el-result
            icon="error"
            :title="error.title"
            :sub-title="error.message"
          >
            <template #extra>
              <el-button type="primary" @click="retryFetch">重试</el-button>
              <el-button @click="$router.push('/')">返回首页</el-button>
            </template>
          </el-result>
        </div>
      </template>

      <template v-else>
        <div class="content-grid">
          <!-- 新闻内容 -->
          <div class="news-content">
            <!-- 标题和编辑按钮 -->
            <div class="title-section">
              <h1 class="title">{{ news.title }}</h1>
              <el-button 
                v-if="canEditNews"
                type="primary"
                @click="showEditDialog"
                class="edit-button"
              >
                <el-icon><Edit /></el-icon>
                <span>修改新闻</span>
              </el-button>
            </div>

            <div class="meta">
              <span class="source">{{ news.source }}</span>
              <span class="time">{{ news.time }}</span>
              <el-tag type="info" size="small">{{ news.category }}</el-tag>
              <span class="author" v-if="news.author">{{ news.author }}</span>
            </div>

            <!-- 文章内容 -->
            <div class="content">
              <!-- HTML 内容 -->
              <div
                v-if="isHtmlContent"
                v-html="news.content"
                class="html-content"
              ></div>

              <!-- 纯文本内容 -->
               <template v-if="!isHtmlContent">
                    <p
                    v-for="(paragraph, index) in formattedContent"
                    :key="index"
                    class="paragraph"
                    v-html="paragraph"
                    ></p>
                </template>

              <!-- 图片展示 -->
              <div
                v-for="(image, index) in news.images"
                :key="'image-' + index"
                class="image-container"
              >
                <el-image
                  :src="image.url"
                  :alt="image.caption"
                  fit="cover"
                  class="content-image"
                  :preview-src-list="news.images.map((img) => img.url)"
                  :initial-index="index"
                  lazy
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><Picture /></el-icon>
                      <span>图片加载失败</span>
                    </div>
                  </template>
                </el-image>
                <!-- <p class="image-caption">{{ image.caption }}</p> -->
              </div>

              <!-- 引用块 -->
              <div class="quote" v-if="news.quote">
                <p>{{ news.quote }}</p>
              </div>
            </div>

            <!-- 统计信息 -->
            <div class="stats-section">
              <div class="stat-item">
                <el-icon><Pointer /></el-icon>
                <span class="stat-value">{{ likeCount  || 0 }}</span>
                <span class="stat-label">点赞</span>
              </div>
              <div class="stat-item">
                <el-icon><Star /></el-icon>
                <span class="stat-value">{{ favoriteCount  || 0 }}</span>
                <span class="stat-label">收藏</span>
              </div>
            </div>

            <!-- 评论区 -->
            <div class="comments-section">
              <h2>评论 ({{ totalComments }})</h2>
              
              <!-- 评论输入框 -->
              <div class="comment-input">
                <el-input
                  v-model="commentText"
                  type="textarea"
                  :rows="3"
                  placeholder="写下你的评论..."
                  resize="none"
                  :disabled="!userStore.token"
                ></el-input>
                <div class="comment-actions">
                  <el-button 
                    type="primary" 
                    @click="submitComment"
                    :loading="commentSubmitting"
                    :disabled="!userStore.token"
                  >
                    {{ commentSubmitting ? '发布中...' : '发表评论' }}
                  </el-button>
                  <span v-if="!userStore.token" class="login-tip">
                    请<a href="/login" class="login-link">登录</a>后发表评论
                  </span>
                </div>
              </div>

              <!-- 评论列表 -->
              <div class="comment-list">
                    <div v-if="comments.length === 0" class="no-comments">
                    <el-empty description="暂无评论" />
                    </div>
                    
                    <template v-else>
                    <div
                        v-for="comment in comments"
                        :key="comment.id"
                        class="comment-item"
                    >
                        <el-avatar
                        :size="40"
                        :src="comment.avatar"
                        class="comment-avatar"
                        />
                        <div class="comment-content">
                        <div class="comment-header">
                            <span class="username">{{ comment.username }}</span>
                            <span class="time">{{ comment.time }}</span>
                            <div class="comment-actions">
                            <el-button
                                v-if="canDeleteComment(comment)"
                                type="danger"
                                size="small"
                                @click="deleteComment(comment.id)"
                                >删除</el-button
                            >
                            <el-button
                                link
                                @click="likeComment(comment.id)"
                                class="like-button"
                            >
                                <el-icon><Pointer /></el-icon>
                                <span>{{ comment.likeCount }}</span>
                            </el-button>
                            <el-button
                                link
                                size="small"
                                @click="toggleReply(comment.id)"
                                class="reply-button"
                            >
                                {{ activeReplyCommentId === comment.id ? '取消回复' : '回复' }}
                            </el-button>
                            </div>
                        </div>
                        <div class="comment-text">{{ comment.content }}</div>
                        
                        <!-- 回复数量及切换按钮 -->
                        <div v-if="comment.replies.length > 0" class="replies-toggle">
                            <el-button link @click="toggleReplies(comment)" class="toggle-button">
                            <el-icon>
                                <ArrowDown v-if="!comment.showReplies" />
                                <ArrowUp v-else />
                            </el-icon>
                            {{ comment.showReplies ? '隐藏回复' : `查看回复(${comment.replies.length})` }}
                            </el-button>
                        </div>
                        
                        <!-- 回复输入框 -->
                        <div v-if="activeReplyCommentId === comment.id" class="reply-input">
                            <el-input
                            v-model="replyText"
                            type="textarea"
                            :rows="2"
                            placeholder="写下你的回复..."
                            resize="none"
                            ></el-input>
                            <div class="reply-actions">
                            <el-button size="small" @click="cancelReply">取消</el-button>
                            <el-button 
                                type="primary" 
                                size="small" 
                                @click="submitReply(comment.id)"
                                :loading="replying"
                            >
                                回复
                            </el-button>
                            </div>
                        </div>
                        
                        <!-- 子评论容器 -->
                        <div class="replies-container" v-if="comment.replies.length > 0 && comment.showReplies">
                            <div
                            v-for="reply in comment.replies"
                            :key="reply.id"
                            class="comment-item reply-item"
                            >
                            <el-avatar
                                :size="32"
                                :src="reply.avatar"
                                class="comment-avatar"
                            />
                            <div class="comment-content">
                                <div class="comment-header">
                                <span class="username">{{ reply.username }}</span>
                                <span class="time">{{ reply.time }}</span>
                                <div class="comment-actions">
                                    <el-button
                                    v-if="canDeleteComment(reply)"
                                    type="danger"
                                    size="small"
                                    @click="deleteComment(reply.id)"
                                    >删除</el-button
                                    >
                                    <el-button
                                    link
                                    @click="likeComment(reply.id)"
                                    class="like-button"
                                    >
                                    <el-icon><Pointer /></el-icon>
                                    <span>{{ reply.likeCount }}</span>
                                    </el-button>
                                </div>
                                </div>
                                <div class="comment-text">
                                <span class="reply-to">@{{ getCommentAuthor(reply.parentCommentId) }}</span>
                                {{ reply.content }}
                                </div>
                            </div>
                            </div>
                        </div>
                        </div>
                    </div>
                    </template>
                </div>
              
              <!-- 加载更多 -->
              <div v-if="hasMoreComments" class="load-more">
                <el-button 
                  type="text" 
                  @click="loadMoreComments"
                  :loading="loadingMore"
                >
                  加载更多评论
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </template>
    </div>

    <!-- 编辑新闻对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="修改新闻"
      width="80%"
      top="5vh"
      class="edit-dialog"
    >
      <div class="edit-form">
        <el-form
          ref="editFormRef"
          :model="editFormData"
          :rules="editRules"
          label-width="80px"
        >
          <!-- 标题 -->
          <el-form-item label="标题" prop="title">
            <el-input
              v-model="editFormData.title"
              placeholder="请输入新闻标题（5-50字）"
              maxlength="50"
              show-word-limit
              size="large"
            />
          </el-form-item>

          <!-- 分类 -->
          <el-form-item label="分类" prop="categoryId">
            <el-select 
              v-model="editFormData.categoryId" 
              placeholder="请选择新闻分类" 
              size="large"
              style="width: 100%"
            >
              <el-option
                v-for="item in categories"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <!-- 封面图片 -->
          <el-form-item label="封面图片">
            <el-upload
              class="cover-uploader"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :http-request="handleUpload"
              accept="image/*"
            >
              <img v-if="editFormData.picPath" :src="editFormData.picPath" class="cover-image" />
              <div v-else class="upload-placeholder">
                <el-icon class="upload-icon"><Plus /></el-icon>
                <p>点击上传封面图片</p>
                <p class="upload-tip">支持 jpg、png 格式，大小不超过 2MB</p>
              </div>
            </el-upload>
          </el-form-item>

          <!-- 摘要 -->
          <el-form-item label="摘要">
            <el-input
              v-model="editFormData.summary"
              type="textarea"
              :rows="3"
              placeholder="请输入新闻摘要，简要描述新闻内容..."
              maxlength="200"
              show-word-limit
            />
          </el-form-item>

          <!-- 内容 -->
          <el-form-item label="内容" prop="content">
            <el-input
              v-model="editFormData.content"
              type="textarea"
              :rows="10"
              placeholder="请输入新闻内容..."
            />
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="submitEdit"
            :loading="submitting"
          >
            {{ submitting ? '保存中...' : '保存修改' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed, reactive } from "vue";
import { useRoute } from "vue-router";
import { Picture, Star,Pointer,Edit,Plus,Loading,ArrowDown, ArrowUp } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";
import { useUserStore } from "@/store/user";
import img from '@/assets/images/doro.jpg'

const route = useRoute();
const userStore = useUserStore();

const likeCount = ref(0);
const favoriteCount = ref(0);

// 新闻相关状态
const news = ref({});
const loading = ref(false);
const error = ref(null);

// 编辑相关
const editDialogVisible = ref(false);
const editFormRef = ref(null);
const editFormData = reactive({
  title: '',
  categoryId: '',
  picPath: '',
  summary: '',
  content: ''
});
const categories = ref([]);
const submitting = ref(false);

// 评论相关状态
const comments = ref([]);
const commentText = ref("");
const replyText = ref("");
const activeReplyCommentId = ref(null);
const commentSubmitting = ref(false);
const replying = ref(false);
const currentPage = ref(1);
const pageSize = 10;
const totalComments = ref(0);
const loadingMore = ref(false);
const hasMoreComments = computed(() => comments.value.length < totalComments.value);

// 添加切换回复显示/隐藏的方法
const toggleReplies = (comment) => {
  comment.showReplies = !comment.showReplies;
};

// 编辑表单验证规则
const editRules = {
  title: [
    { required: true, message: '请输入新闻标题', trigger: 'blur' },
    { min: 5, max: 50, message: '标题长度应在 5 到 50 个字符之间', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择新闻分类', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入新闻内容', trigger: 'blur' },
    { min: 10, message: '内容不能少于 10 个字符', trigger: 'blur' }
  ]
};

// 判断是否有编辑权限
const canEditNews = computed(() => {
  return userStore.userInfo?.id === news.value.authorId || userStore.userInfo?.role === 'admin'
});

// 判断内容是否为HTML
const isHtmlContent = computed(() => {
  if (!news.value?.content) return false;
  const content = news.value.content;
  return /<[a-z][\s\S]*>/i.test(content);
});

// 将内容按段落分割（用于纯文本显示）
const contentParagraphs = computed(() => {
  if (!news.value?.content || isHtmlContent.value) return [];
  return news.value.content.split("\n").filter((p) => p.trim());
});

// 获取新闻详情
const fetchNewsDetail = async (newsId) => {
  loading.value = true;
  error.value = null;
  try {
    const response = await axios.get(`/app/news/detail/${newsId}`);

    if (response.data.code === 200 && response.data.data) {
      const newsData = response.data.data;
      
      // 转换数据格式以匹配前端显示需求
      news.value = {
        id: newsData.id,
        title: newsData.title,
        content: newsData.content,
        contentParagraphs: contentParagraphs.value,
        source: "课头条",
        time: newsData.createDate,
        category: getCategoryName(newsData.categoryId),
        author: newsData.author,
        authorId: newsData.authorId,
        images: newsData.picPath
          ? [
              {
                url: newsData.picPath,
                caption: newsData.summary || newsData.title,
              },
            ]
          : [],
        quote: newsData.summary,
    //     likeCount: newsData.likeCount || 0,
    //   favoriteCount: newsData.favoritesCount || 0
      };
      
      // 确保传递 newsId 参数
      await fetchLikeCount(newsData.id);
      await fetchFavoriteCount(newsData.id); // 添加这行
    } else {
      error.value = {
        title: "获取新闻失败",
        message: "新闻不存在或已被删除",
      };
    }
  } catch (err) {
    console.error("获取新闻详情失败:", err);
    error.value = {
      title: "获取新闻失败",
      message: err.response?.data?.msg || "服务器错误，请稍后重试",
    };
  } finally {
    loading.value = false;
  }
};

// 获取分类数据
const fetchCategories = async () => {
  try {
    const response = await axios.get('/app/categories');
    if (response.data.code === 200) {
      categories.value = response.data.data;
    } else {
      ElMessage.error('获取分类失败');
    }
  } catch (error) {
    console.error('获取分类失败:', error);
    ElMessage.error('获取分类失败，请刷新重试');
  }
};

// 显示编辑对话框
const showEditDialog = () => {
  // 填充表单数据
  editFormData.title = news.value.title
  editFormData.categoryId = getCategoryIdByName(news.value.category)
  editFormData.picPath = news.value.images[0]?.url || ''
  editFormData.summary = news.value.quote || ''
  editFormData.content = news.value.content
  
  editDialogVisible.value = true
};

// 根据分类名称获取分类ID
const getCategoryIdByName = (name) => {
  const category = categories.value.find(c => c.name === name)
  return category ? category.id : ''
};

// 提交修改
const submitEdit = async () => {
  try {
    await editFormRef.value.validate();
    submitting.value = true;
    
    const response = await axios.put(`/app/news/update`, {
      id: news.value.id, // 确保包含新闻ID
      title: editFormData.title,
      categoryId: editFormData.categoryId,
      picPath: editFormData.picPath,
      summary: editFormData.summary,
      content: editFormData.content,
      authorId: news.value.authorId // 保持作者不变
    });
    
    if (response.data.code === 200) {
      ElMessage.success(response.data.msg || '新闻修改成功');
      editDialogVisible.value = false;
      // 重新加载新闻数据
      await fetchNewsDetail(news.value.id);
    } else {
      ElMessage.error(response.data.msg || '修改失败');
    }
  } catch (error) {
    if (error.response?.data?.msg) {
      ElMessage.error(error.response.data.msg);
    } else if (error !== 'cancel') {
      console.error('修改新闻失败:', error);
      ElMessage.error('修改失败，请重试');
    }
  } finally {
    submitting.value = false;
  }
};

const formattedContent = computed(() => {
  if (!news.value?.content) return [];
  // 将换行符转换为段落
  return news.value.content.split('\n').filter(p => p.trim());
});

// 图片上传处理
const beforeUpload = (file) => {
  const isValidFormat = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type);
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isValidFormat) {
    ElMessage.error('图片只能是 JPG、PNG 或 GIF 格式!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!');
    return false;
  }
  return true;
};

const handleUpload = async (options) => {
  try {
    const uploadFormData = new FormData();
    uploadFormData.append('file', options.file);

    const response = await axios.post('/app/upload', uploadFormData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

    if (response.data.code === 200) {
      editFormData.picPath = response.data.data;
      ElMessage.success('封面图片上传成功');
    } else {
      ElMessage.error(response.data.message || '图片上传失败');
    }
  } catch (error) {
    console.error('图片上传失败:', error);
    ElMessage.error('图片上传失败，请重试');
  }
};

// 根据分类ID获取分类名称
const getCategoryName = (categoryId) => {
  const categoryMap = {
    1: "热点新闻",
    2: "研发编程",
    3: "虚拟现实",
    4: "产品运营",
    5: "视觉创意",
    6: "职场考试",
    7:"体育新闻",
    8:"财经新闻"
  };
  return categoryMap[categoryId] || "其他";
};

// 重试获取数据
const retryFetch = async () => {
  if (route.params.id) {
    error.value = null;
    await Promise.all([fetchNewsDetail(route.params.id), fetchComments()]);
  } else {
    error.value = {
      title: "参数错误",
      message: "未找到新闻ID",
    };
  }
};

// 获取点赞数
const fetchLikeCount = async (newsId) => {
  try {
     console.log("1111111"+newsId)
    const response = await axios.get(`/api/like/getLikeCount/${newsId}`);
    if (response.data.code === 200) {
      likeCount.value = response.data.data || 0;
       console.log("111111");

    }
  } catch (error) {
    console.error("获取点赞数失败:", error);
    likeCount.value = 0;
  }
};

// 获取收藏数
const fetchFavoriteCount = async (newsId) => {
  try {
    const response = await axios.get(`/api/favorites/getFavoritesCount/${newsId}`);
    if (response.data.code === 200) {
      favoriteCount.value = response.data.data || 0;
    }
  } catch (error) {
    console.error("获取收藏数失败:", error);
    favoriteCount.value = 0;
  }
};

// 获取评论列表
const fetchComments = async (page = 1) => {
  try {
    const response = await axios.get(`/app/comments/list/${route.params.id}`, {
      params: {
        page,
        pageSize
      }
    });
    
    if (response.data.code === 200) {
      const processComments = (comments) => {
        return comments.map(comment => ({
          id: comment.commentId,
          userId: comment.userId,
          username: comment.userName,
          avatar: comment.avatar || img,
          content: comment.commentText,
          time: formatTime(comment.createTime),
          likeCount: comment.likeCount || 0,
          parentCommentId: comment.parentCommentId,
          isReply: comment.parentCommentId !== 0,
          showReplies: false,
          replies: comment.childrenComments ? processComments(comment.childrenComments) : []
        }));
      };

      const processedComments = processComments(response.data.data.list);
      
      if (page === 1) {
        comments.value = processedComments;
      } else {
        comments.value = [...comments.value, ...processedComments];
      }
      
      totalComments.value = response.data.data.total || 0;
    }
  } catch (error) {
    console.error("获取评论列表失败:", error);
    ElMessage.error(error.response?.data?.msg || "获取评论列表失败");
  }
};
// 加载更多评论
const loadMoreComments = async () => {
  if (loadingMore.value) return;
  
  loadingMore.value = true;
  try {
    const nextPage = currentPage.value + 1;
    const response = await axios.get(`/app/comments/list/${route.params.id}`, {
      params: {
        page: nextPage,
        pageSize
      }
    });
    
    if (response.data.code === 200) {
      const newComments = response.data.data.list.map(comment => ({
        id: comment.commentId,
        userId: comment.userId,
        username: comment.userName,
        avatar: comment.avatar || "/default-avatar.png",
        content: comment.commentText,
        time: formatTime(comment.createTime),
        likeCount: comment.likeCount || 0,
        replyCount: comment.replyCount || 0,
        parentCommentId: comment.parentCommentId,
        isReply: !!comment.parentCommentId,
        replies: []
      }));
      
      // 过滤掉已经存在的评论（防止重复）
      const existingCommentIds = new Set([
        ...comments.value.map(c => c.id),
        ...comments.value.flatMap(c => c.replies.map(r => r.id))
      ]);
      
      const filteredNewComments = newComments.filter(
        comment => !existingCommentIds.has(comment.id)
      );
      
      if (filteredNewComments.length > 0) {
        // 分离顶级评论和回复
        const topLevelComments = filteredNewComments.filter(c => !c.isReply);
        const replyComments = filteredNewComments.filter(c => c.isReply);
        
        // 将回复关联到对应的父评论
        topLevelComments.forEach(comment => {
          comment.replies = replyComments
            .filter(reply => reply.parentCommentId === comment.id)
            .sort((a, b) => new Date(a.time) - new Date(b.time));
        });
        
        // 添加到现有评论列表
        comments.value = [...comments.value, ...topLevelComments];
        currentPage.value = nextPage;
      } else {
        // 如果没有新评论，不再增加页码，避免跳过可能的评论
        ElMessage.info("没有更多新评论了");
      }
    } else {
      ElMessage.error(response.data.msg || "加载更多评论失败");
    }
  } catch (error) {
    console.error("加载更多评论失败:", error);
    ElMessage.error(error.response?.data?.msg || "加载更多评论失败");
  } finally {
    loadingMore.value = false;
  }
};

// 提交评论
const submitComment = async () => {
  if (!commentText.value.trim()) {
    ElMessage.warning("请输入评论内容");
    return;
  }

  if (!userStore.token) {
    ElMessage.warning("请先登录");
    return;
  }

  try {
    commentSubmitting.value = true;
    const response = await axios.post("/app/comments/add", {
      contentId: route.params.id,
      commentText: commentText.value.trim(),
      parentCommentId: null,
      userId: userStore.userInfo.id
    });

    if (response.data.code === 200) {
      ElMessage.success(response.data.msg || "评论发布成功");
      commentText.value = "";
      // 刷新评论列表
      await fetchComments();
      totalComments.value += 1;
    } else {
      ElMessage.error(response.data.msg || "评论发布失败");
    }
  } catch (error) {
    console.error("发布评论失败:", error);
    if (error.response?.data?.msg) {
      ElMessage.error(error.response.data.msg);
    } else {
      ElMessage.error("发布评论失败");
    }
  } finally {
    commentSubmitting.value = false;
  }
};

// 提交回复
// 提交回复
// 提交回复
const submitReply = async (parentCommentId) => {
  if (!replyText.value.trim()) {
    ElMessage.warning("请输入回复内容");
    return;
  }

  try {
    replying.value = true;
        // 先保存回复内容，因为后面会清空输入框
    const replyContent = replyText.value.trim();
    // 1. 查找被回复的评论内容和用户ID
    let repliedContent = '';
    let repliedUserId = null;
    
    // 在顶级评论中查找
    const parentComment = comments.value.find(c => c.id === parentCommentId);
    if (parentComment) {
      repliedContent = parentComment.content;
      repliedUserId = parentComment.userId;
    } else {
      // 在回复中查找
      for (const comment of comments.value) {
        const reply = comment.replies.find(r => r.id === parentCommentId);
        if (reply) {
          repliedContent = reply.content;
          repliedUserId = reply.userId;
          break;
        }
      }
    }

    // 2. 提交回复
    const response = await axios.post("/app/comments/add", {
      contentId: route.params.id,
      commentText:replyContent,
      parentCommentId,
      userId: userStore.userInfo.id
    });

    if (response.data.code === 200) {
      ElMessage.success(response.data.msg || "回复成功");
      replyText.value = "";
      activeReplyCommentId.value = null;
      
      // 3. 添加回复到评论列表
      const parentComment = comments.value.find(c => c.id === parentCommentId);
      if (parentComment) {
        parentComment.replies.push({
          id: response.data.data.commentId,
          userId: userStore.userInfo.id,
          username: userStore.userInfo.username,
          avatar: userStore.userInfo.avatar || "/default-avatar.png",
          content: replyText.value.trim(),
          time: "刚刚",
          likeCount: 0,
          parentCommentId,
          isReply: true
        });
        parentComment.replyCount += 1;
        fetchComments();
      }
      totalComments.value += 1;

      // 4. 发送系统通知（如果不是回复自己）
      if (repliedUserId && repliedUserId !== userStore.userInfo.id) {
        try {
          const noticeResponse = await axios.post("/api/systemNotice/add", {
            content:replyContent ,  // 
            createTime: new Date().toISOString(),
            userId: repliedUserId,
            status: "unread",
            title: `${userStore.userInfo.username}回复了你的评论: ${repliedContent.substring(0, 30)}${repliedContent.length > 30 ? '...' : ''}`,
            type: "reminder"
          });
          
          if (noticeResponse.data.code !== 200) {
            console.error("发送通知失败:", noticeResponse.data.msg);
          }
        } catch (noticeError) {
          console.error("发送通知出错:", noticeError);
        }
      }
    } else {
      ElMessage.error(response.data.msg || "回复失败");
    }
  } catch (error) {
    console.error("回复失败:", error);
    if (error.response?.data?.msg) {
      ElMessage.error(error.response.data.msg);
    } else {
      ElMessage.error("回复失败");
    }
  } finally {
    replying.value = false;
  }
};

// 切换回复显示/隐藏
const toggleReply = (commentId) => {
  if (activeReplyCommentId.value === commentId) {
    activeReplyCommentId.value = null;
  } else {
    activeReplyCommentId.value = commentId;
  }
};

// 取消回复
const cancelReply = () => {
  activeReplyCommentId.value = null;
  replyText.value = "";
};

// 删除评论
const deleteComment = async (commentId) => {
  try {
    await ElMessageBox.confirm("确定要删除这条评论吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const response = await axios.delete(`/app/comments/delete/${commentId}`);
    if (response.data.code === 200) {
      ElMessage.success(response.data.msg || "评论删除成功");
      
      // 处理删除顶级评论
      const commentIndex = comments.value.findIndex(c => c.id === commentId);
      if (commentIndex !== -1) {
        // 减少总评论数（包括回复）
        totalComments.value -= (1 + comments.value[commentIndex].replies.length);
        comments.value.splice(commentIndex, 1);
      } else {
        // 处理删除回复
        for (const comment of comments.value) {
          const replyIndex = comment.replies.findIndex(r => r.id === commentId);
          if (replyIndex !== -1) {
            comment.replies.splice(replyIndex, 1);
            comment.replyCount -= 1;
            totalComments.value -= 1;
            break;
          }
        }
      }
    } else {
      ElMessage.error(response.data.msg || "删除评论失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除评论失败:", error);
      ElMessage.error(error.response?.data?.msg || "删除评论失败");
    }
  }
};

// 点赞评论
const likeComment = async (commentId) => {
  if (!userStore.token) {
    ElMessage.warning("请先登录");
    return;
  }

  try {
    const response = await axios.put(`/app/comments/like/${commentId}`, {
      increment: 1
    });

    if (response.data.code === 200) {
      // 更新顶级评论点赞数
      const comment = comments.value.find(c => c.id === commentId);
      if (comment) {
        comment.likeCount += 1;
      } else {
        // 更新回复点赞数
        for (const parentComment of comments.value) {
          const reply = parentComment.replies.find(r => r.id === commentId);
          if (reply) {
            reply.likeCount += 1;
            break;
          }
        }
      }
    } else {
      ElMessage.error(response.data.msg || "点赞失败");
    }
  } catch (error) {
    console.error("点赞失败:", error);
    ElMessage.error(error.response?.data?.msg || "点赞失败");
  }
};

// 获取被回复的用户名
const getCommentAuthor = (parentCommentId) => {
  // 先查找顶级评论
  const parentComment = comments.value.find(c => c.id === parentCommentId);
  if (parentComment) return parentComment.username;
  
  // 如果顶级评论中没找到，查找回复中的评论
  for (const comment of comments.value) {
    const reply = comment.replies.find(r => r.id === parentCommentId);
    if (reply) return reply.username;
  }
  
  return "已删除用户";
};

// 判断是否有权限删除评论
const canDeleteComment = (comment) => {
  // 管理员可以删除任何评论
  if (userStore.userInfo?.role === 'admin') return true;
  // 评论作者可以删除自己的评论
  if (userStore.userInfo?.id === comment.userId) return true;
  // 新闻作者可以删除自己文章下的评论
  if (userStore.userInfo?.id === news.value.authorId) return true;
  return false;
};

// 格式化时间
const formatTime = (timeString) => {
  if (!timeString) return "";
  const date = new Date(timeString);
  const now = new Date();
  const diff = now - date;

  if (diff < 60000) return "刚刚";
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`;
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`;
  if (diff < 2592000000) return `${Math.floor(diff / 86400000)}天前`;
  
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
};

// 监听路由变化
watch(
  () => route.params.id,
  (newId) => {
    if (newId) {
      fetchNewsDetail(newId);
      fetchComments();
    }
  }
);

onMounted(() => {
  if (route.params.id) {
    fetchNewsDetail(route.params.id);
    fetchComments();
    fetchCategories();
  } else {
    error.value = {
      title: "参数错误",
      message: "未找到新闻ID",
    };
  }
});
</script>
<style scoped>
.home {
  min-height: 100vh;
  background-image: url("/images/blueArchive2.jpg");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;
}

.news-detail {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.breadcrumb {
  margin-bottom: 25px;
  font-size: 14px;
  color: #606266;
}

.content-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 30px;
}

.news-content {
  background: #fff;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

/* 标题区域样式 */
.title-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap;
  gap: 15px;
}

.title {
  font-size: 28px;
  font-weight: bold;
  line-height: 1.4;
  color: #1a1a1a;
  margin: 0;
}

.edit-button {
  margin-left: auto;
}

.meta {
  display: flex;
  align-items: center;
  margin-bottom: 25px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
  color: #666;
  font-size: 14px;
}

.meta > * {
  margin-right: 20px;
}

.meta .el-tag {
  padding: 0 8px;
}

.content {
  margin: 30px 0;
  line-height: 1.8;
  color: #2c3e50;
}

.html-content {
  line-height: 1.8;
}

.html-content :deep(p) {
  margin: 1em 0;
}

.html-content :deep(img) {
  max-width: 100%;
  height: auto;
  margin: 1em 0;
  border-radius: 4px;
}

.html-content :deep(a) {
  color: #409eff;
  text-decoration: none;
}

.html-content :deep(a:hover) {
  text-decoration: underline;
}

.html-content :deep(h1),
.html-content :deep(h2),
.html-content :deep(h3),
.html-content :deep(h4),
.html-content :deep(h5),
.html-content :deep(h6) {
  margin: 1.5em 0 1em;
  line-height: 1.4;
}

.html-content :deep(ul),
.html-content :deep(ol) {
  padding-left: 2em;
  margin: 1em 0;
}

.html-content :deep(blockquote) {
  margin: 1em 0;
  padding: 0.5em 1em;
  border-left: 4px solid #409eff;
  background-color: #f8f9fa;
  color: #666;
}

.paragraph {
  margin: 1em 0;
  text-align: justify;
}

.image-container {
  margin: 30px 0;
  text-align: center;
}

.content-image {
  max-width: 100%;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.image-caption {
  margin-top: 10px;
  font-size: 14px;
  color: #666;
  text-align: center;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
}

.image-error .el-icon {
  font-size: 40px;
  margin-bottom: 10px;
}

.quote {
  margin: 30px 0;
  padding: 15px 20px;
  border-left: 4px solid #409eff;
  background-color: #f5f7fa;
  font-style: italic;
  color: #666;
}


.stats-section {
  display: flex;
  gap: 30px;
  margin: 30px 0;
  padding: 20px 0;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
  justify-content: center;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  color: #666;
}

.stat-item .el-icon {
  font-size: 20px;
}

.stat-value {
  font-weight: bold;
  color: #333;
}

.comments-section {
  margin-top: 50px;
  padding-top: 30px;
  border-top: 1px solid #eee;
}

.comments-section h2 {
  font-size: 22px;
  margin-bottom: 25px;
  color: #333;
}

.comment-item {
  display: flex;
  padding: 20px 0;
  border-bottom: 1px solid #eee;
}

.comment-avatar {
  margin-right: 15px;
  flex-shrink: 0;
}

.comment-content {
  flex: 1;
  min-width: 0;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  flex-wrap: wrap;
  gap: 8px;
}

.username {
  font-weight: bold;
  margin-right: 10px;
}

.time {
  font-size: 13px;
  color: #999;
  margin-right: auto;
}

.comment-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.like-button {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 0;
  color: #666;
}

.like-button:hover {
  color: #409eff;
}

.comment-text {
  color: #333;
  line-height: 1.6;
  word-break: break-word;
}

.comment-article {
  margin-top: 8px;
  font-size: 12px;
  color: #666;
  padding: 4px 8px;
  background: #f5f5f5;
  border-radius: 4px;
  display: inline-block;
}

.comment-input {
  margin-top: 30px;
}

.comment-actions {
  margin-top: 15px;
  text-align: right;
}

.error-container {
  background: #fff;
  border-radius: 8px;
  padding: 40px;
  text-align: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.no-comments {
  padding: 40px 0;
  text-align: center;
  background: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
}

/* 编辑对话框样式 */
.edit-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.edit-form {
  max-height: 70vh;
  overflow-y: auto;
  padding-right: 10px;
}

/* 滚动条样式 */
.edit-form::-webkit-scrollbar {
  width: 6px;
}

.edit-form::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 3px;
}

.edit-form::-webkit-scrollbar-track {
  background-color: #f1f1f1;
}

/* 封面图片上传 */
.cover-uploader {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 300px;
  height: 180px;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: border-color 0.3s;
}

.cover-uploader:hover {
  border-color: #409eff;
}

.upload-placeholder {
  text-align: center;
  color: #8c939d;
}

.upload-icon {
  font-size: 32px;
  margin-bottom: 8px;
}

.upload-tip {
  font-size: 12px;
  margin-top: 4px;
  color: #999;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
/* 新增样式 */
.replies-toggle {
  margin-top: 10px;
}

.toggle-button {
  padding: 0;
  font-size: 13px;
  color: #666;
}

.toggle-button:hover {
  color: #409eff;
}

.replies-container {
  margin-top: 10px;
  border-left: 2px solid #f0f0f0;
  padding-left: 15px;
}

.reply-item {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #eee;
}

.reply-to {
  color: #409eff;
  margin-right: 5px;
}
/* --------------------- */
/* 添加或修改以下样式 */
/* .comment-item {
  position: relative;
}

.reply-item {
  margin-left: 56px; 
  padding-top: 16px;
  border-top: 1px dashed #eee;
  border-bottom: none;
}

.reply-item .comment-avatar {
  width: 32px;
  height: 32px;
  margin-right: 12px;
}

.reply-item .comment-content {
  font-size: 14px;
}

.reply-to {
  color: #409eff;
  margin-right: 5px;
}

.replies-container {
  margin-top: 10px;
  border-left: 2px solid #f0f0f0;
  padding-left: 10px;
} */
</style>